<template>
  <div class="category-container">
    <!-- 左侧分类栏 -->
    <div class="category-sidebar">
      <div class="sidebar-header">
        <h2>分类</h2>
      </div>
      <div class="category-list">
        <div
          v-for="category in categories"
          :key="category.id"
          class="category-item"
          :class="{ active: currentCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          <el-icon :size="24">
            <component :is="category.icon" />
          </el-icon>
          <span>{{ category.name }}</span>
        </div>
      </div>
    </div>

    <!-- 右侧商品区域 -->
    <div class="content-area">
      <!-- 顶部筛选栏 -->
      <div class="filter-bar">
        <div class="filter-left">
          <el-select v-model="sortBy" placeholder="排序方式" class="filter-select">
            <el-option label="最新发布" value="newest" />
            <el-option label="价格从低到高" value="price-asc" />
            <el-option label="价格从高到低" value="price-desc" />
          </el-select>
          <el-select v-model="schoolFilter" placeholder="选择学校" class="filter-select">
            <el-option label="全部学校" value="" />
            <el-option
              v-for="school in schools"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            />
          </el-select>
          <el-switch
            v-model="onlySameCity"
            class="filter-switch"
            active-text="仅看同城"
          />
        </div>
        <div class="filter-right">
          <el-button type="primary" :icon="Filter">筛选</el-button>
        </div>
      </div>

      <!-- 商品网格 -->
      <div class="products-grid">
        <transition-group name="fade-scale" tag="div" class="grid-container">
          <div
            v-for="product in filteredProducts"
            :key="product.id"
            class="product-card"
            @click="navigateToProduct(product.id)"
          >
            <div class="product-image-wrapper">
              <el-image
                :src="product.image"
                fit="cover"
                loading="lazy"
                :preview-src-list="[product.image]"
              >
                <template #placeholder>
                  <div class="image-placeholder">
                    <el-skeleton-item variant="image" />
                  </div>
                </template>
              </el-image>
              <div class="product-badges">
                <span v-if="product.condition === 'new'" class="badge new">全新</span>
                <span v-else class="badge used">{{ product.condition }}成新</span>
                <span v-if="product.freeShipping" class="badge shipping">包邮</span>
              </div>
              <el-button
                class="favorite-btn"
                :class="{ active: product.isFavorite }"
                circle
                @click.stop="toggleFavorite(product)"
              >
                <el-icon><Star /></el-icon>
              </el-button>
            </div>
            
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
              <p class="product-price">¥{{ product.price }}</p>
              <p class="product-desc">{{ product.description }}</p>
              <div class="product-meta">
                <span class="school-name">{{ product.school }}</span>
                <span class="publish-time">{{ formatTime(product.publishTime) }}</span>
              </div>
            </div>
          </div>
        </transition-group>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Filter, Star } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

dayjs.extend(relativeTime)
const router = useRouter()

// 状态
const currentCategory = ref('')
const sortBy = ref('newest')
const schoolFilter = ref('')
const onlySameCity = ref(false)

// 模拟数据
const categories = ref([
  { id: '1', name: '数码产品', icon: 'Monitor' },
  { id: '2', name: '图书教材', icon: 'Reading' },
  { id: '3', name: '生活用品', icon: 'House' },
  { id: '4', name: '服装鞋包', icon: 'ShoppingBag' },
  { id: '5', name: '运动健身', icon: 'Basketball' },
])

const schools = ref([
  { id: '1', name: '北京大学' },
  { id: '2', name: '清华大学' },
  // ... 更多学校
])

// 方法
const selectCategory = (categoryId: string) => {
  currentCategory.value = categoryId
}

const toggleFavorite = async (product: any) => {
    try {
        // 产品ID不存在时不进行操作
        if (!product.id) {
            ElMessage.error('商品信息不完整，无法收藏');
            return;
        }

        // 检查用户是否已登录
        const userInfo = localStorage.getItem('userInfo');
        const token = localStorage.getItem('token');
        if (!userInfo || !token) {
            ElMessage.warning('请先登录后再收藏商品');
            router.push('/login?redirect=' + encodeURIComponent(router.currentRoute.value.fullPath));
            return;
        }

        // 获取当前用户ID
        const parsedUserInfo = JSON.parse(userInfo);
        const userId = parsedUserInfo.id;
        
        if (!userId) {
            ElMessage.warning('请先登录后再收藏商品');
            return;
        }

        // 判断当前是否已收藏
        const isFavorited = product.isFavorite;
        
        // 根据当前状态决定是收藏还是取消收藏
        let response;
        if (isFavorited) {
            // 取消收藏
            response = await request.delete(`/products/${product.id}/favorite?userId=${userId}`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
        } else {
            // 添加收藏
            response = await request.post(`/products/${product.id}/favorite`, { userId }, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
        }

        // 检查响应是否成功
        if (response && (response.code === 200 || response.status === 200)) {
            // 更新商品的收藏状态
            product.isFavorite = !isFavorited;
            
            // 提示用户操作结果
            ElMessage.success(isFavorited ? '已取消收藏' : '收藏成功');
        } else {
            // 操作失败
            ElMessage.error(response?.message || (isFavorited ? '取消收藏失败' : '收藏失败'));
        }
    } catch (error) {
        console.error('收藏操作失败:', error);
        ElMessage.error('操作失败，请稍后重试');
    }
}

const formatTime = (timestamp: number) => {
  return dayjs(timestamp).fromNow()
}

// 导航到商品详情页
const navigateToProduct = (productId: string | number) => {
  router.push(`/product/${productId}`)
}

// 计算属性
const filteredProducts = computed(() => {
  // 实现筛选逻辑
  return []
})
</script>

<style scoped>
.category-container {
  display: flex;
  min-height: 100vh;
  background-color: #F8F8F8;
  font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "PingFang SC", sans-serif;
}

/* 左侧分类栏样式 */
.category-sidebar {
  width: 240px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  border-right: 1px solid rgba(0, 0, 0, 0.1);
  padding: 20px 0;
}

.sidebar-header {
  padding: 0 20px 20px;
}

.sidebar-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #1C1C1E;
  margin: 0;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 0 12px;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #1C1C1E;
}

.category-item:hover {
  background-color: rgba(0, 122, 255, 0.1);
}

.category-item.active {
  background-color: #007AFF;
  color: white;
}

/* 右侧内容区域样式 */
.content-area {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

/* 筛选栏样式 */
.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.filter-left {
  display: flex;
  gap: 16px;
  align-items: center;
}

.filter-select {
  width: 160px;
}

/* 商品网格样式 */
.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  padding: 8px;
}

.product-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
}

.product-card:hover {
  transform: scale(1.03);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}

.product-image-wrapper {
  position: relative;
  padding-top: 56.25%; /* 16:9 比例 */
}

.product-image-wrapper .el-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background: #f5f5f5;
}

.product-badges {
  position: absolute;
  top: 12px;
  left: 12px;
  display: flex;
  gap: 8px;
}

.badge {
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.badge.new {
  background: #34C759;
  color: white;
}

.badge.used {
  background: #FF9500;
  color: white;
}

.badge.shipping {
  background: #007AFF;
  color: white;
}

.favorite-btn {
  position: absolute;
  top: 12px;
  right: 12px;
  background: rgba(255, 255, 255, 0.9);
  border: none;
  color: #8E8E93;
}

.favorite-btn.active {
  color: #FF2D55;
}

.product-info {
  padding: 16px;
}

.product-name {
  font-size: 17px;
  font-weight: 600;
  color: #1C1C1E;
  margin: 0 0 8px;
  line-height: 1.4;
}

.product-price {
  font-size: 18px;
  font-weight: 700;
  color: #FF3B30;
  margin: 0 0 8px;
}

.product-desc {
  font-size: 14px;
  color: #8E8E93;
  margin: 0 0 12px;
  line-height: 1.4;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #C7C7CC;
}

/* 动画效果 */
.fade-scale-enter-active,
.fade-scale-leave-active {
  transition: all 0.3s ease;
}

.fade-scale-enter-from,
.fade-scale-leave-to {
  opacity: 0;
  transform: scale(0.9);
}

@media (max-width: 768px) {
  .category-container {
    flex-direction: column;
  }

  .category-sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  }

  .category-list {
    flex-direction: row;
    overflow-x: auto;
    padding: 12px;
    gap: 12px;
  }

  .category-item {
    flex: 0 0 auto;
  }

  .filter-bar {
    flex-direction: column;
    gap: 16px;
  }

  .filter-left {
    width: 100%;
    flex-wrap: wrap;
  }

  .filter-select {
    width: 100%;
  }
}
</style> 